﻿using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;

namespace EstimatesTool.Util;

public class ExcelUtil
{
    private readonly static List<int> ColumnsWidths = new()
    {
        5*256, 60 *256, 30*256 ,10*256, 10*256, 10*256, 10*256, 10*256, 70* 256, 10*256
    };


    public static string OutPutSourceList(DataTable dt, bool IsCompare, string outPath)
    {
        var workbook = new XSSFWorkbook();
        ISheet sheet = workbook.CreateSheet("現行リソース一覧");
        int cols = IsCompare ? 10 : 8;
        var style = workbook.CreateCellStyle();
        style.BorderLeft = BorderStyle.Thin;
        style.BorderRight = BorderStyle.Thin;
        style.BorderTop = BorderStyle.Thin;
        style.BorderBottom = BorderStyle.Thin;
        style.LeftBorderColor = HSSFColor.Black.Index;
        style.RightBorderColor = HSSFColor.Black.Index;
        style.TopBorderColor = HSSFColor.Black.Index;
        style.BottomBorderColor = HSSFColor.Black.Index;
        style.VerticalAlignment = VerticalAlignment.Center;
        style.Alignment = HorizontalAlignment.Center;
        style.FillForegroundColor = HSSFColor.LightGreen.Index;
        style.FillPattern = FillPattern.SolidForeground;
        var fisrt = sheet.CreateRow(0);
        for (int i = 0; i < cols; i++)
        {
            sheet.SetColumnWidth(i, ColumnsWidths[i]);
            var cell = fisrt.CreateCell(i);
            cell.SetCellValue(dt.Columns[i].ColumnName);
            cell.CellStyle = style;
        }

        var style2 = workbook.CreateCellStyle();
        style2.BorderLeft = BorderStyle.Thin;
        style2.BorderRight = BorderStyle.Thin;
        style2.BorderTop = BorderStyle.Thin;
        style2.BorderBottom = BorderStyle.Thin;
        style2.LeftBorderColor = HSSFColor.Black.Index;
        style2.RightBorderColor = HSSFColor.Black.Index;
        style2.TopBorderColor = HSSFColor.Black.Index;
        style2.BottomBorderColor = HSSFColor.Black.Index;
        style2.VerticalAlignment = VerticalAlignment.Center;
        style2.Alignment = HorizontalAlignment.Center;
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var dr = dt.Rows[i];
            dr[0] = $"{i+1}";
            var row = sheet.CreateRow(i + 1);
            for (int j = 0; j < cols; j++)
            {
                var cell = row.CreateCell(j);
                cell.CellStyle = style2;
                cell.SetCellValue($"{dr[j]}");
            }
        }
        var outfile = Path.Combine(outPath, $"現行リソース一覧_{DateTime.Now:yyyyMMddHHmmss}.xlsx");
        using var fs = new FileStream(outfile, FileMode.Create, FileAccess.Write);
        workbook.Write(fs);
        return Path.GetFileName(outfile);
    }
}
